package com.da.javatest.algorithm;

/**
 * @author chenlida
 * @date 2019/3/30 16:10
 * @description
 */
public class BinarySearch {
    public int binarySearch1(int[] a, int val) {
        int start = 0;
        int end = a.length - 1;
        while (start <= end) {
            int mid = start + (end - start) / 2;
            if (a[mid] > val) {
                end = mid - 1;
            } else if (a[mid] < val) {
                start = mid + 1;
            } else {
                return mid;
            }
        }
        return -1;
    }

    public int binarySearch(int[] a, int val) {
        return bSear(a, val, 0, a.length - 1);
    }

    private int bSear(int[] a, int val, int start, int end) {
        if (start > end) { return -1; }
        int mid = start + (end - start) / 2;
        if (a[mid] == val) {
            return mid;
        } else if (a[mid] > val) {
            end = mid - 1;
        } else {
            start = mid + 1;
        }
        return bSear(a, val, start, end);
    }
}
